package com.demo.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

/**
 * mybatis 工具类
 * 
 */
public class MybatisUtil {


	private static SqlSessionFactory sqlSessionFactory;
	/**
	 * 读取mybatis配置文件创建sqlSessionFactory
	 */
	static {
		String resource = "mybatis-config.xml";
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("创建sqlSessionFactory失败;详细信息:"+e.getMessage());
		}
	}

	/**
	 * 获取sqlSession
	 * 
	 * @param autoCommit true:自动提交事务 false:手动提交事务
	 * @return
	 * @throws Exception
	 */
	public  static SqlSession getSqlSession(boolean autoCommit) throws Exception {
		SqlSession sqlSession = null;
		try {
			sqlSession = sqlSessionFactory.openSession(autoCommit);
		} catch (Exception e) {
			throw new Exception("创建sqlSession异常,详细信息:" + e.getMessage(),e);
		}

		return sqlSession;
	}

	/**
	 * 提交事务
	 * 
	 * @param sqlSession
	 * @throws Exception
	 */
	public static void commit(SqlSession sqlSession) {
		if (sqlSession != null) {
			sqlSession.commit();
		}
	}

	/**
	 * 回滚事务
	 * 
	 * @param sqlSession
	 * @throws Exception
	 */
	public static void rollback(SqlSession sqlSession) {
		if (sqlSession != null) {
			sqlSession.rollback();
		}
	}

	/**
	 * 关闭sqlSession 同时也会关闭conn
	 * 
	 * @param sqlSession
	 * @throws Exception
	 */
	public static void close(SqlSession sqlSession) {
		if (sqlSession != null) {
			sqlSession.close();
		}
	}

}
